package main;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import org.apache.commons.collections.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ChainBuilderGeneratorPlugin extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {

        try {
            // 立即执行一个后台任务
            WriteCommandAction.runWriteCommandAction(e.getProject(), () -> {
                PsiClass psiClass = PsiHelper.getPsiClassFromContext(e);
                GenerateDialog dlg = new GenerateDialog(psiClass);
                if (dlg.showAndGet()) {

                    Set<String> fieldNames = dlg.getFields().stream().map(x -> x.getName()).collect(Collectors.toSet());
                    if (CollectionUtils.isEmpty(fieldNames)) {
                        return;
                    }

                    //删除已存在的方法
                    Arrays.stream(psiClass.getMethods()).filter(psiMethod -> fieldNames.contains(psiMethod.getName())).forEach(psiMethod -> psiMethod.delete());
                    GenerateImpl.genBuilderMethod(psiClass, dlg.getFields());
                }
            });
        } catch (Throwable e1) {
            //e1.printStackTrace();
            System.out.println(e1.getMessage());
        }
    }
}
